<template>
  <div class="coupon-config-form">
    <el-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      label-width="120px"
      @submit.prevent="handleSubmit"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="站点" prop="siteId" required>
            <el-select 
              v-model="form.siteId" 
              placeholder="请选择站点" 
              style="width: 100%"
              @change="handleSiteChange"
            >
              <el-option 
                v-for="site in sites" 
                :key="site.id" 
                :label="site.name" 
                :value="site.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优惠券" prop="couponId" required>
            <el-select 
              v-model="form.couponId" 
              placeholder="请选择优惠券" 
              style="width: 100%"
              @change="handleCouponChange"
            >
              <el-option 
                v-for="coupon in coupons" 
                :key="coupon.id" 
                :label="coupon.name" 
                :value="coupon.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status" required>
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="展示频率" prop="showFrequency" required>
            <el-select v-model="form.showFrequency" placeholder="请选择展示频率" style="width: 100%">
              <el-option label="仅一次" value="once" />
              <el-option label="每次访问" value="every_visit" />
              <el-option label="每日一次" value="daily" />
              <el-option label="每周一次" value="weekly" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户范围" prop="userScope" required>
            <el-input 
              :value="getUserScopeText(form.userScope)" 
              readonly 
              placeholder="用户范围"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="弹窗规则" prop="popupRuleId" required>
            <el-select 
              v-model="form.popupRuleId" 
              placeholder="请选择弹窗规则" 
              style="width: 100%"
              @change="handlePopupRuleChange"
            >
              <el-option 
                v-for="rule in popupRules" 
                :key="rule.id" 
                :label="rule.name" 
                :value="rule.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item 
        v-if="form.userScope === 'specific_tags'" 
        label="用户标签" 
        prop="userTags"
      >
        <el-select 
          v-model="form.userTags" 
          multiple 
          placeholder="请选择用户标签" 
          style="width: 100%"
        >
          <el-option label="新注册用户" value="new_register" />
          <el-option label="活跃用户" value="active_user" />
          <el-option label="高价值用户" value="high_value" />
          <el-option label="流失风险用户" value="churn_risk" />
        </el-select>
      </el-form-item>



      <!-- 优惠券信息 -->
      <el-divider content-position="left">优惠券信息</el-divider>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="优惠券名称">{{ selectedCoupon?.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="优惠券类型">{{ selectedCoupon?.type || '-' }}</el-descriptions-item>
        <el-descriptions-item label="面值">{{ getCouponValueText() }}</el-descriptions-item>
        <el-descriptions-item label="使用条件">{{ getCouponConditionText() }}</el-descriptions-item>
        <el-descriptions-item label="有效期">{{ getCouponValidityText() }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="selectedCoupon" :type="getCouponStatusType()" size="small">
            {{ getCouponStatusText() }}
          </el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 弹窗规则信息 -->
      <el-divider v-if="form.popupRuleId" content-position="left">弹窗规则信息</el-divider>
      
      <el-descriptions v-if="form.popupRuleId" :column="2" border>
        <el-descriptions-item label="规则名称">{{ selectedRule?.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="触发类型">{{ getTriggerTypeText() }}</el-descriptions-item>
        <el-descriptions-item label="规则描述" :span="2">{{ selectedRule?.description || '-' }}</el-descriptions-item>
        <el-descriptions-item label="用户范围">{{ getUserTypeText() }}</el-descriptions-item>
        <el-descriptions-item label="设备范围">{{ getDeviceTypeText() }}</el-descriptions-item>
      </el-descriptions>


      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存
        </el-button>
        <el-button @click="$emit('cancel')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { Site, Coupon, SiteCouponConfigForm, PopupRule } from '@/types/sitePopup'

// Props
interface Props {
  form: SiteCouponConfigForm
  sites: Site[]
  coupons: Coupon[]
  popupRules: PopupRule[]
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  submit: [SiteCouponConfigForm]
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 选中的站点和优惠券
const selectedSite = computed(() => 
  props.sites.find(site => site.id === props.form.siteId)
)

// 计算属性
const selectedCoupon = computed(() => {
  return props.coupons.find(c => c.id === props.form.couponId)
})

const selectedRule = computed(() => {
  return props.popupRules.find(r => r.id === props.form.popupRuleId)
})

// 表单验证规则
const rules: FormRules = {
  siteId: [
    { required: true, message: '请选择站点', trigger: 'change' }
  ],
  couponId: [
    { required: true, message: '请选择优惠券', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  showFrequency: [
    { required: true, message: '请选择展示频率', trigger: 'change' }
  ],
  userScope: [
    { required: true, message: '请选择用户范围', trigger: 'change' }
  ],
  popupRuleId: [
    { required: true, message: '请选择弹窗规则', trigger: 'change' }
  ],
  userTags: [
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (props.form.userScope === 'specific_tags' && (!value || value.length === 0)) {
          callback(new Error('请选择用户标签'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 监听用户范围变化
watch(() => props.form.userScope, (newScope) => {
  if (newScope !== 'specific_tags') {
    props.form.userTags = []
  }
})

// 方法
const handleSiteChange = () => {
  // 可以在这里添加站点切换后的逻辑
}

const handleCouponChange = () => {
  // 可以在这里添加优惠券切换后的逻辑
}

const handlePopupRuleChange = () => {
  // 可以在这里添加弹窗规则切换后的逻辑
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    

    
    emit('submit', { ...props.form })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 优惠券相关函数
const getCouponValueText = () => {
  if (!selectedCoupon.value) return '-'
  const coupon = selectedCoupon.value
  if (coupon.type === '满减券') {
    return `满${coupon.minAmount}减${coupon.value}`
  } else if (coupon.type === '折扣券') {
    return `${(coupon.value * 10).toFixed(1)}折`
  } else if (coupon.type === '包邮券') {
    return '包邮'
  } else {
    return `立减${coupon.value}`
  }
}

const getCouponConditionText = () => {
  if (!selectedCoupon.value) return '-'
  const coupon = selectedCoupon.value
  if (coupon.minAmount) {
    return `满${coupon.minAmount}可用`
  }
  return '无门槛'
}

const getCouponValidityText = () => {
  if (!selectedCoupon.value) return '-'
  const coupon = selectedCoupon.value
  return `${coupon.validStart} 至 ${coupon.validEnd}`
}

const getCouponStatusType = () => {
  if (!selectedCoupon.value) return 'info'
  const statusMap: Record<string, string> = {
    'draft': 'info',
    'published': 'success',
    'expired': 'warning',
    'disabled': 'danger'
  }
  return statusMap[selectedCoupon.value.status] || 'info'
}

const getCouponStatusText = () => {
  if (!selectedCoupon.value) return '-'
  const statusMap: Record<string, string> = {
    'draft': '草稿',
    'published': '已发布',
    'expired': '已过期',
    'disabled': '已禁用'
  }
  return statusMap[selectedCoupon.value.status] || selectedCoupon.value.status
}

// 弹窗规则相关函数
const getTriggerTypeText = () => {
  if (!selectedRule.value) return '-'
  const typeMap: Record<string, string> = {
    'immediate': '立即触发',
    'delay': '延迟触发',
    'exit_intent': '退出意图'
  }
  return typeMap[selectedRule.value.triggerType] || selectedRule.value.triggerType
}

const getUserTypeText = () => {
  if (!selectedRule.value) return '-'
  const typeMap: Record<string, string> = {
    'all': '全部用户',
    'new': '新用户',
    'returning': '老用户',
    'vip': 'VIP用户'
  }
  return typeMap[selectedRule.value.showConditions.userType] || selectedRule.value.showConditions.userType
}

const getDeviceTypeText = () => {
  if (!selectedRule.value) return '-'
  const typeMap: Record<string, string> = {
    'all': '全部设备',
    'desktop': '桌面端',
    'mobile': '移动端'
  }
  return typeMap[selectedRule.value.showConditions.deviceType] || selectedRule.value.showConditions.deviceType
}

const getUserScopeText = (scope: string) => {
  const scopeMap: Record<string, string> = {
    'all': '全部用户',
    'new_user': '新用户',
    'vip_user': 'VIP用户',
    'specific_tags': '指定标签'
  }
  return scopeMap[scope] || scope
}
</script>

<style scoped>
.coupon-config-form {
  padding: 20px 0;
}

.coupon-info {
  margin: 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-descriptions) {
  margin-top: 16px;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #303133;
}
</style>
